const {exec ,spawn}  =require("child_process")

// 异步执行命令 
function executeCommand(command, args) {
  return new Promise((resolve, reject) => {
    const childProcess = spawn(command, args);

    let output = '';

    childProcess.stdout.on('data', (data) => {
      output += data.toString();
    });

    childProcess.stderr.on('data', (data) => {
      console.error(data.toString());
    });

    childProcess.on('error', (error) => {
      reject(error);
    });

    childProcess.on('close', (code) => {
      if (code === 0) {
        resolve(output);
      } else {
        reject(new Error(`Command failed with code ${code}`));
      }
    });
    setTimeout(() => {
      resolve(1)
      childProcess.kill(); // 在10秒后强制终止子进程
    }, 60000)
  });
}
// 
function executeCommandWithTimeout(command, timeout) {
  return new Promise((resolve, reject) => {
    const childProcess = spawn(command, { shell: true });
    let output = '';

    const timeoutId = setTimeout(() => {
      childProcess.kill();
      // reject(new Error('Command execution timed out.'));
    }, timeout);

    childProcess.stdout.on('data', (data) => {
      output += data.toString();
    });

    childProcess.stderr.on('data', (data) => {
      output += data.toString();
    });

    childProcess.on('exit', (code) => {
      clearTimeout(timeoutId);
      if (code === 0) {
        resolve(output);
      } else {
        reject(new Error(`Command execution failed with exit code ${code}.`));
      }
    });
  });
}

module.exports = {
  executeCommand,
  executeCommandWithTimeout
  
}